package com.example.order.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/6/18 0:22
 */
@RestController
@RequestMapping("/hystrix")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {


    // 使用 Hystrix，fallbackMethod 值为该接口调用失败执行的回调函数名称
    // 该回调函数返回值必须与接口返回值类型相同
    //    @HystrixCommand(
    //            fallbackMethod = "fallback",
    //            commandProperties = {
    //                    // 设置超时时间，单位 ms，默认 1000ms
    //                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    //            })

    @HystrixCommand(
            // 服务熔断配置
            commandProperties = {
                    // 开启断路器
                    @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
                    // 断路器的最小请求数
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "20"),
                    // 断路器滚动窗口时间
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "5000"),
                    // 断路器打开的错误百分比条件
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50"),
            }
    )
    @GetMapping("/getProductInfoList")
    public String getProductList(@RequestParam Integer number) {

        if (number % 2 == 0) {
            return "success";
        }
        else {
            throw new RuntimeException("远程调用服务出错");
            // 使用template调用服务
//            RestTemplate restTemplate = new RestTemplate();
//            String res = restTemplate.postForObject("http://localhost:8080//product/listForOrder",
//                    Collections.singletonList("157875196366160022"),
//                    String.class);
//            return res;
        }
    }

    private String fallback() {
        return "fallback 服务调用失败了，请稍后重试。";
    }

    private String defaultFallback() {
        return "defaultFallback 服务调用失败了，请稍后重试。";
    }
}
